import React,{ Component } from 'react';
import { connect } from 'dva';
import styles from './CartPage.css';
import {Checkbox} from 'antd-mobile';
import CartItem from '../components/CartItem';
class CartPage extends Component {
    constructor(props){
        super(props);
        this.clickItem = this.clickItem.bind(this);
        this.state = {
            allprice:0,
            itemincart:[],
        }
    }
    buycart(){
        const {itemincart: cart} = this.state;
        this.props.dispatch({type:'pay/createOrder', payload:{cart}})
    }
    clickItem(state, item) {
        console.log(item);
        let itemincart = this.state.itemincart;
        let allprice = 0;
        const getitem = {
            price: item.price,
            id: item.lecture_id,
        }
        itemincart.push(getitem);
        if (state) {
            this.setState({itemincart: itemincart});
            itemincart.map(val=>{
                allprice+= val.price;
                return val;
            })
            this.setState({allprice:allprice});
        } else {
            let cutitemincart = itemincart.filter(val=>{
                return (val.id !== item.lecture_id);
            })
            this.setState({itemincart:cutitemincart});
            cutitemincart.map(val => {
                allprice+=val.price;
                return val;
            });
            this.setState({allprice:allprice});

        }
    }
    componentDidMount() {
        this.props.dispatch({type:'classrelation/getCart'});
    }

    render() {

    const {classrelation:{cart}} = this.props;
    return (
        <div> 
            {cart.map((val,key)=>{
                return (
                    <CartItem 
                        key = {key}
                        data = {val}
                        clickit = {this.clickItem}
                    />
                );
            })}
            <div className = {styles.bottombar}>
                <div className = {styles.pricestate}>
                    <div className = {styles.checkbutton}>
                    <span>
                        全选
                    </span>
                    <Checkbox className = {styles.checkbutton}/>
                    </div>
                    <div className = {styles.pricenum}>
                    <span> 
                        金额总计：{this.state.allprice}
                    </span>
                    </div>
                </div>
                <div 
                    onClick = {()=>this.buycart()}
                    className = {styles.buybutton}
                >
                    <span>结算</span>
                </div>
            </div>
        </div>
    );
    }
};

function mapStateToProps({classrelation, pay}) {
  return {
    classrelation,
    pay
  }
}
export default connect(mapStateToProps)(CartPage);
